package com.thread;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.hccp.net.CookieManager;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.model.CardTable;
import com.model.Fakecard;
import com.model.LoginStatus;
import com.model.UserInfo;
import com.model.User_Card;
import com.util.PropertiesUtil;

public class LoginThread implements Runnable {

	private Lock LoginLock = new ReentrantLock();
	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	private String COOKIE;
	private Document doc;
	private String session_id;
	private String account;
	private String password;
	private boolean LoginFlag=false;
	
	
	private Label cardNum;
	private Label label_friend;
	private Label label_gacha_ticket;
	private Label label_fsp;
	private Label label_gold;
	private Label lable_show_bc;
	private Label lable_show_ap;
	private Label lable_remain_rewards;
	private Button btn_logout;
	private Button btn_login;
	private Table fairytable;
	private Text text_main_show;
	private Text text_password;
	private Text text_acount;
	protected Shell shell;
	private Label cookie_lable;


	private DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
	private String remain_rewards="";
	private NodeList fairy_event;
	private UserInfo userinfo=null;
	private String errorMSG;

	@Override
	public void run() {
		// TODO Auto-generated method stub
		LoginLock.lock();
		try {
			 
			DocumentBuilder db = dbf.newDocumentBuilder();

			System.out.print("进程1/4...");
			URL urlLog = new URL(
					"http://game1-CBT.ma.sdo.com:10001/connect/app/login?&login_id="
							+ account + "&password=" + password);
			HttpURLConnection.setFollowRedirects(false);
			HttpURLConnection connection_pre = (HttpURLConnection) urlLog
					.openConnection();

			InputStream is = connection_pre.getInputStream();
			COOKIE = connection_pre.getHeaderField("Set-Cookie");
			System.out.println("Cookie:" + COOKIE + " "
					+ connection_pre.getResponseMessage());

			HttpURLConnection.setFollowRedirects(true);

			System.out.print("进程2/4...");
			urlLog = new URL(
					"http://game1-CBT.ma.sdo.com:10001/connect/app/login?&login_id="
							+ account + "&password=" + password);
			HttpURLConnection connection = (HttpURLConnection) urlLog
					.openConnection();
			connection.setRequestMethod("POST");
			connection.addRequestProperty("Cookie", COOKIE);
			is = connection.getInputStream();

			doc = db.parse(is);

			NodeList nodes = doc.getChildNodes();
			System.out.println(nodes.getLength());
			System.out.println(nodes.item(0).getNodeType());
			System.out.println(nodes.item(0).getChildNodes().getLength());
			getTree(nodes.item(0), 0);
			String error = doc.getElementsByTagName("error").item(0)
					.getTextContent();
			if (!error.equals("0")) {
				this.errorMSG = error;
				LoginFlag=false;
			}
			session_id = doc.getElementsByTagName("session_id").item(0)
					.getTextContent();
			LoginFlag=true;
		} catch (Exception e) {
			e.printStackTrace();
			LoginFlag=false;
		}finally{
			if(LoginFlag){
				Display.getDefault().asyncExec(new Runnable() {
					
					

					@Override
					public void run() {
						// TODO Auto-generated method stub
						text_main_show.append("[" + df.format(new Date())
								+ "]:登录成功！\n");
						text_main_show.append("[" + df.format(new Date()) + "]:"
								+ "cookie:" + COOKIE+ "\n");
						cookie_lable.setText(COOKIE);
//						isLogin = true;
						btn_login.setEnabled(false);
						btn_logout.setEnabled(true);
						text_acount.setEnabled(false);
						text_password.setEnabled(false);
						userinfo=get_userinfo();
						String max_ap=userinfo.getMax_ap();
						String max_bc=userinfo.getMax_bc();
						String current_ap=userinfo.getCurrent_ap();
						String current_bc=userinfo.getCurrent_bc();
						String gold=userinfo.getGold();
						String friendship_point=userinfo.getFriendship_point();
						String friends=userinfo.getFriends();
						String friend_max=userinfo.getFriend_max();
						String gacha_ticket=userinfo.getGacha_ticket();
						lable_show_ap.setText(current_ap+"/"+max_ap);
						lable_show_bc.setText(current_bc+"/"+max_bc);
						label_gold.setText(gold);
						label_fsp.setText(friendship_point);
						label_friend.setText(friends+"/"+friend_max);
						label_gacha_ticket.setText(gacha_ticket);
						int ownCardNum=userinfo.getOwner_card_list().size();
						
						cardNum.setText(ownCardNum+"/200");
						String fairySelect_result="";
						while(!(fairySelect_result=fairySelect()).equals("success")){
							if(fairySelect_result.equals("false")){
								text_main_show.append("[" + df.format(new Date())
										+ "]:请重新获取妖精信息...\n");
								break;
							}
						}
						lable_remain_rewards.setText(remain_rewards);
						fairytable.removeAll();
						for(int i=0;i<fairy_event.getLength();i++){
							 String find_username=fairy_event.item(i).getChildNodes().item(0).getChildNodes().item(1).getTextContent();
							 String fairy_name=fairy_event.item(i).getChildNodes().item(1).getChildNodes().item(1).getTextContent();
							 String fairy_lv=fairy_event.item(i).getChildNodes().item(1).getChildNodes().item(2).getTextContent();
							 String fairy_hp="--/--";
							 String escape_time_second=fairy_event.item(i).getChildNodes().item(1).getChildNodes().item(3).getTextContent();
							 String put_down=fairy_event.item(i).getChildNodes().item(2).getTextContent();
							 String find_user_id=fairy_event.item(i).getChildNodes().item(0).getChildNodes().item(0).getTextContent();
							 String fairy_id=fairy_event.item(i).getChildNodes().item(1).getChildNodes().item(0).getTextContent();
							 String escape_time;
							 if(escape_time_second.equals("0")||put_down.equals("2")){
								 escape_time="已逃走";
							 }else{
								 TableItem tit= new TableItem(fairytable,SWT.CENTER);
								 int h = Integer.parseInt(escape_time_second) / 3600;
								 int m = (Integer.parseInt(escape_time_second) % 3600) / 60;
								 int s = Integer.parseInt(escape_time_second) % 60;
								 escape_time=h+":"+m+":"+s;
								 tit.setText(new String[]{fairy_name,fairy_lv,fairy_hp,find_username,escape_time,find_user_id,fairy_id});
							 }
							 
						}
					}
				});
			}else{
				Display.getDefault().asyncExec(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub

						if (!errorMSG.equals("")) {
							text_main_show.append("[" + df.format(new Date())
									+ "]:" + errorMSG + "\n");
//							text_main_show.append("[" + df.format(new Date())
//									+ "]:" + "登录失败，请重新尝试...\n");
						}else{
							text_main_show.append("[" + df.format(new Date())
									+ "]:登录失败，正在尝试重新连接...\n");
						}
					
					}
				});
				LoginThread loginthread=new LoginThread(cookie_lable, session_id, account, password, cardNum, label_friend, label_gacha_ticket, label_fsp, label_gold, lable_show_bc, lable_show_ap, lable_remain_rewards, btn_logout, btn_login, fairytable, text_main_show, text_password, text_acount, shell, remain_rewards, fairy_event, userinfo);
				new Thread(loginthread).start();
			}
		}
	
	}
	
	
	public UserInfo get_userinfo() {
		UserInfo userinfo = new UserInfo();
		userinfo.setSession_id(session_id);
		userinfo.setGold((doc.getElementsByTagName("gold").item(0).getTextContent()));
		userinfo.setName(doc.getElementsByTagName("name").item(0)
				.getTextContent());
		userinfo.setLeader_serial_id(doc
				.getElementsByTagName("leader_serial_id").item(0)
				.getTextContent());
		userinfo.setTown_level(doc.getElementsByTagName("town_level").item(0)
				.getTextContent());
		userinfo.setPercentage(doc.getElementsByTagName("percentage").item(0)
				.getTextContent());
		userinfo.setCurrent_ap(doc.getElementsByTagName("ap").item(0)
				.getChildNodes().item(0).getTextContent());
		userinfo.setMax_ap(doc.getElementsByTagName("ap").item(0)
				.getChildNodes().item(1).getTextContent());
		userinfo.setLast_update_time_ap(doc.getElementsByTagName("ap").item(0)
				.getChildNodes().item(3).getTextContent());
		userinfo.setCurrent_bc(doc.getElementsByTagName("bc").item(0)
				.getChildNodes().item(0).getTextContent());
		userinfo.setMax_bc(doc.getElementsByTagName("bc").item(0)
				.getChildNodes().item(1).getTextContent());
		userinfo.setLast_update_time_bc(doc.getElementsByTagName("bc").item(0)
				.getChildNodes().item(3).getTextContent());
		userinfo.setMax_card_num(doc.getElementsByTagName("max_card_num")
				.item(0).getTextContent());
		userinfo.setFree_ap_bc_point(doc
				.getElementsByTagName("free_ap_bc_point").item(0)
				.getTextContent());
		userinfo.setFriendship_point(doc
				.getElementsByTagName("friendship_point").item(0)
				.getTextContent());
		userinfo.setEx_gauge(doc.getElementsByTagName("ex_gauge").item(0)
				.getTextContent());
		userinfo.setGacha_ticket(doc.getElementsByTagName("gacha_ticket")
				.item(0).getTextContent());
		userinfo.setDeck_rank(doc.getElementsByTagName("deck_rank").item(0)
				.getTextContent());
		userinfo.setFriends(doc.getElementsByTagName("friends").item(0)
				.getTextContent());
		userinfo.setFriend_max(doc.getElementsByTagName("friend_max").item(0)
				.getTextContent());
		userinfo.setFriends_invitations(doc
				.getElementsByTagName("friends_invitations").item(0)
				.getTextContent());
		userinfo.setNotice_of_menu(doc.getElementsByTagName("notice_of_menu")
				.item(0).getTextContent());
		userinfo.setGacha_point(doc.getElementsByTagName("gacha_point").item(0)
				.getTextContent());
		userinfo.setFairy_appearance(doc
				.getElementsByTagName("fairy_appearance").item(0)
				.getTextContent());
		userinfo.setOwner_card_list(getUserCardLsit());
		userinfo.setItemlist(getItemlist());
		userinfo.setLogin(getLogin());
		userinfo.setFakecardlist(getFakecardlist());
		userinfo.setGreeting(doc.getElementsByTagName("greeting").item(0)
				.getTextContent());
		return userinfo;
	}
	
	
	public LoginThread(Label cookie_lable,String session_id, String account, String password,
		Label cardNum, Label label_friend,
		Label label_gacha_ticket, Label label_fsp, Label label_gold,
		Label lable_show_bc, Label lable_show_ap, Label lable_remain_rewards,
		Button btn_logout, Button btn_login, Table fairytable,
		Text text_main_show, Text text_password, Text text_acount, Shell shell,
		String remain_rewards,
		NodeList fairy_event,UserInfo userinfo) {
	super();
	this.cookie_lable = cookie_lable;
	this.session_id = session_id;
	this.account = account;
	this.password = password;
	this.cardNum = cardNum;
	this.label_friend = label_friend;
	this.label_gacha_ticket = label_gacha_ticket;
	this.label_fsp = label_fsp;
	this.label_gold = label_gold;
	this.lable_show_bc = lable_show_bc;
	this.lable_show_ap = lable_show_ap;
	this.lable_remain_rewards = lable_remain_rewards;
	this.btn_logout = btn_logout;
	this.btn_login = btn_login;
	this.fairytable = fairytable;
	this.text_main_show = text_main_show;
	this.text_password = text_password;
	this.text_acount = text_acount;
	this.shell = shell;
	this.remain_rewards = remain_rewards;
	this.fairy_event = fairy_event;
	this.userinfo = userinfo;
}

	public ArrayList<User_Card> getUserCardLsit() {
		ArrayList<User_Card> user_card_list = new ArrayList<User_Card>();
		NodeList nodes = doc.getElementsByTagName("owner_card_list").item(0)
				.getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			User_Card user_card = new User_Card();
			user_card.setSerial_id(nodes.item(i).getChildNodes().item(0)
					.getTextContent());
			user_card.setMaster_card_id(nodes.item(i).getChildNodes().item(1)
					.getTextContent());
			user_card.setHolography(nodes.item(i).getChildNodes().item(2)
					.getTextContent());
			user_card.setHp(nodes.item(i).getChildNodes().item(3)
					.getTextContent());
			user_card.setPower(nodes.item(i).getChildNodes().item(4)
					.getTextContent());
			user_card.setCritical(nodes.item(i).getChildNodes().item(5)
					.getTextContent());
			user_card.setLv(nodes.item(i).getChildNodes().item(6)
					.getTextContent());
			user_card.setLv_max(nodes.item(i).getChildNodes().item(7)
					.getTextContent());
			user_card.setExp(nodes.item(i).getChildNodes().item(8)
					.getTextContent());
			user_card.setMax_exp(nodes.item(i).getChildNodes().item(9)
					.getTextContent());
			user_card.setNext_exp(nodes.item(i).getChildNodes().item(10)
					.getTextContent());
			user_card.setExp_diff(nodes.item(i).getChildNodes().item(11)
					.getTextContent());
			user_card.setExp_per(nodes.item(i).getChildNodes().item(12)
					.getTextContent());
			user_card.setSale_price(nodes.item(i).getChildNodes().item(13)
					.getTextContent());
			user_card.setMaterial_price(nodes.item(i).getChildNodes().item(14)
					.getTextContent());
			user_card.setEvolution_price(nodes.item(i).getChildNodes().item(15)
					.getTextContent());
			user_card.setPlus_limit_count(nodes.item(i).getChildNodes()
					.item(16).getTextContent());
			user_card.setLimit_over(nodes.item(i).getChildNodes().item(17)
					.getTextContent());
			user_card_list.add(user_card);
		}
		return user_card_list;
	}

	public Map<String, String> getItemlist() {
		Map<String, String> itemlist = new HashMap<String, String>();
		NodeList nodes = doc.getElementsByTagName("itemlist");
		for (int i = 0; i < nodes.getLength(); i++) {
			itemlist.put(nodes.item(i).getNodeName(), nodes.item(i)
					.getTextContent());
		}
		return itemlist;
	}

	public LoginStatus getLogin() {
		LoginStatus login = new LoginStatus();
		NodeList nodes = doc.getElementsByTagName("login");
		login.setUser_id(nodes.item(0).getChildNodes().item(0).getTextContent());
		login.setPush_fairy_yell(nodes.item(0).getChildNodes().item(1).getTextContent());
		login.setPush_good(nodes.item(0).getChildNodes().item(2).getTextContent());
		return login;
	}

	public ArrayList<Fakecard> getFakecardlist() {
		ArrayList<Fakecard> fakecardlist = new ArrayList<Fakecard>();
		NodeList nodes = doc.getElementsByTagName("fakecard");
		for (int i = 0; i < nodes.getLength(); i++) {
			Fakecard fakecard = new Fakecard();
			fakecard.setKnight_id(nodes.item(i).getChildNodes().item(0)
					.getTextContent());
			fakecard.setParts_no(nodes.item(i).getChildNodes().item(1)
					.getTextContent());
			fakecard.setCount(nodes.item(i).getChildNodes().item(2)
					.getTextContent());
			fakecardlist.add(fakecard);
		}
		return fakecardlist;
	}
	
	
	private String fairySelect() {
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			URL urlLog = new URL(
					"http://117.121.6.138:10001/connect/app/menu/fairyselect?cyt=1");
			HttpURLConnection connection = (HttpURLConnection) urlLog
					.openConnection();
			connection.setRequestMethod("POST");
			connection.addRequestProperty("Cookie", COOKIE);
			InputStream is = connection.getInputStream();

			doc = db.parse(is);
			fairy_event=doc.getElementsByTagName("fairy_event");
			remain_rewards=doc.getElementsByTagName("remaining_rewards").item(0).getTextContent();
			
			return "success";
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return "noLogin";
		}catch(NullPointerException e){
			e.printStackTrace();
			return "noLogin";
		}catch(Exception e){
			e.printStackTrace();
			return "false";
		}
	}
	
	public static void getTree(Node node, int times) {
		for (int i = 0; i < times; i++) {
			System.out.print("\t");
		}
		if (node.getNodeValue() != null) {
			System.out.print(node.getNodeValue() + "\n");
		} else {
			System.out.print(node.getNodeName() + "\n");
		}
		if (node.hasChildNodes()) {
			// System.out.print("\t"+node.getNodeName()+"\n");
			for (int i = 0; i < node.getChildNodes().getLength(); i++) {
				getTree(node.getChildNodes().item(i), times + 1);
			}
		} else {
			// System.out.print("\t"+node.getNodeName()+"\n");
		}
	}

}
